import Vue from 'vue'
import { addRouter } from '@/router'
import router from '@/router'
import command from '@/utils/command'
Vue.use(command)

const state = {
  routerMap: null,
  current: {},
  currentRoutes: [],
  list: [],
  operations: [],
  init: false,
  searchRoutes: [],
  remoteMenu: [],
  remoteMenuList: []
}
const mutations = {
  SET_ROUTER_MAP: (state, data) => {
    state.routerMap = data
  },
  UPDATE_CURRENT: (state, data) => {
    state.current = data
  },
  SET_CURRENT_ROUTES (state, data) {
    state.currentRoutes = data || []
  },
  SET_MENU_ROUTES_LIST (state, data) {
    state.list = data
  },
  SET_INIT (state, data) {
    state.init = data
  },
  SET_OPERATIONS: (state, operations) => {
    state.operations = [...new Set(state.operations.concat(operations))]
  },
  SET_SEARCH_ROUTES: (state, routes) => {
    state.searchRoutes = routes
  },
  SET_REMOTE_MENU_ROUTES: (state, routes) => {
    state.remoteMenu = state.remoteMenu.concat(routes)
  },
  SET_REMOTE_MENU_LIST_ROUTES: (state, routes) => {
    state.remoteMenuList = state.remoteMenuList.concat(routes)
  }
}

function initRouter (router, data) {
  let list = data || []
  router.map((items) => {
    if (!items.hidden) {
      // items.initials = pinyin.getFullChars(items.meta.title)
      items.text = items.meta.title
      items.icon = items.meta.icon
      list.push(items)
    }
    if (items.children) {
      initRouter(items.children, list)
    }
  })
  return list
}

function iteration (router, parentList) {
  const list = parentList || []
  router.map((e) => {
    if (e.operations && e.operations.length) {
      for (const operation of e.operations) {
        if (operation.operationId) {
          if (!/^\//g.test(operation.operationId)) {
            operation.operationId = '/' + operation.operationId
          }
          list.push(operation.operationId)
        }
      }
    }
    if (e.items && e.items.length) {
      iteration(e.items, list)
    }
  })
  return list
}

const actions = {
  /**
   * 登陆后获取资源权限
   */
  async getAuthirizes ({ commit, dispatch, state }, I_resId) {
    let userInfo = localStorage.getItem('currentMember') ? JSON.parse(localStorage.getItem('currentMember')) : null
    if (!userInfo) return
    return new Promise(async (resolve, reject) => {
      command.executeCommand({
        api: '/api/',
        data: {}
      }).then(async (result) => {
        let data = result.data
        commit('SET_OPERATIONS', data)
        commit('SET_REMOTE_MENU_LIST_ROUTES', data)
        resolve(data)
      })
    })
  },

  setRouter ({ commit }, body) {
    console.log('bodybody', body)
    const operations = [...new Set(iteration(body))]
    commit('SET_OPERATIONS', operations)
    const newRouter = addRouter(body)
    initRouter(newRouter)
    console.log('newRouter', newRouter)
    commit('SET_ROUTER_MAP', newRouter)
    // localStorage.setItem('LAST_ROUTER', JSON.stringify(body))
    // if (body.isTab) {
    //   // 刷新当前页面
    //   const href = location.href
    //   location.href = href
    // }
  },

  getCurrentRoutes ({ commit, state }, payload) {
    const currentRoute = payload
    const { routes: newRoutes } = router.options

    if (currentRoute.name) {
      const currParentRoute = newRoutes.filter((v) =>
        currentRoute.matched.some(
          (r) => r.path === v.path || r.redirect === v.path
        )
      )[0]
      if (currParentRoute && currParentRoute.children) {
        const childrens = currParentRoute.children.map((children) => {
          if (!/^\/\w/gi.test(children.path)) {
            children.path = currParentRoute.path + '/' + children.path
          }
          return children
        })
        commit('SET_CURRENT_ROUTES', childrens)
      }
    }
  },
  setInit ({ commit, state }, payload) {
    commit('SET_INIT', payload)
  },
  // 搜索菜单路由列表
  setSearchRoutes ({ commit, state }, payload) {

    let list = []
    for (const route of payload) {
      const child = route.children
      if (child === undefined) {
        continue
      }
      for (const childRoute of child) {
        if (!childRoute.text) continue
        const newRoute = {
          ...childRoute,
          fullName: `${route.text}>${childRoute.text}`
        }
        list.push(newRoute)
      }
    }
    commit('SET_SEARCH_ROUTES', list)
  },
}

function toList (list, tree) {
  tree.forEach((e) => {
    list.push(e)
    if (e.items && e.items.length) {
      toList(list, e.items)
    }
  })
  return list
}

export default {
  namespaced: true,
  mutations,
  state,
  actions,
}
